from business import CommandResolver, CommandHandler, UART_Command
from config import config, ConfigController
from http_server import HttpServer
from io import led
from log import Log
from net import WifiWrapper, WifiConnectTask, NetworkStatusTask, NetworkStatus
from timer import TickTimer
from uart import UART_ReceiveTask, uart_2
from upgrade import UpgradeController

log = Log(tag='Main')
tick_timer = TickTimer()


def main():
    led.on()
    report_mac()
    init_timer()
    tick_timer.start()
    sync_time()


def report_mac():
    UART_Command.report_mac(NetworkStatus.get_mac())


def sync_time():
    UART_Command.send_get_time_command()


handler = None


def on_wifi_ready():
    UART_Command.clean_screen()


def init_server():
    server = HttpServer()
    server.mapping.add_mapping('/config', ConfigController())
    server.mapping.add_mapping('/upgrade', UpgradeController())
    return server


def init_timer():
    global handler
    handler = CommandHandler()
    resolver = CommandResolver(handler)
    tick_timer.add_task(UART_ReceiveTask(uart_2, lambda data: resolver.append_command(data)))

    wifi_wrapper = WifiWrapper(config.net())
    wifi_connect_task = WifiConnectTask(wifi_wrapper, lambda: UART_Command.show('Connecting WIFI...'),
                                        on_wifi_ready)
    tick_timer.add_task(wifi_connect_task)
    tick_timer.add_task(NetworkStatusTask())
    tick_timer.add_task(init_server())


if __name__ == '__main__':
    if config.is_ready():
        main()
    else:
        UART_Command.show('CERR[%s]' % config.err_msg)
        revert_config()
